// Created by Chengfu Zou
// Copyright (C) FYT Vision Group. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef RM_UTILS_TRAJECTORY_COMPENSATOR_HPP_
#define RM_UTILS_TRAJECTORY_COMPENSATOR_HPP_

#include <Eigen/Dense>
#include <memory>
#include <tuple>

namespace fyt {

class TrajectoryCompensator {
public:
  TrajectoryCompensator() = default;
  virtual ~TrajectoryCompensator() = default;

  // Compensate the trajectory of the bullet, return the pitch increment
  bool compensate(const Eigen::Vector3d &target_position, double &pitch) const noexcept;

  virtual double getFlyingTime(const Eigen::Vector3d &target_position) const noexcept = 0;

  std::vector<std::pair<double, double>> getTrajectory(double distance,
                                                       double angle) const noexcept;

  double velocity = 15.0;
  int iteration_times = 20;
  double gravity = 9.8;
  double resistance = 0.01;

protected:
  // Calculate the trajectory of the bullet, return the vertical impact point
  virtual double calculateTrajectory(const double x, const double angle) const noexcept = 0;
};

// IdealCompensator does not consider the air resistance
class IdealCompensator : public TrajectoryCompensator {
public:
  double getFlyingTime(const Eigen::Vector3d &target_position) const noexcept override;

protected:
  double calculateTrajectory(const double x, const double angle) const noexcept override;
};

// ResistanceCompensator considers the air resistance
class ResistanceCompensator : public TrajectoryCompensator {
public:

  // 国际标准大气模型：随高度 (m) 变化的气体密度 (kg/m^3)
inline double airDensity(double h) const{
    const double rho0 = 1.225;
    const double T0   = 288.15;
    const double L    = 0.0065;
    const double R    = 287.05;
    const double g    = 9.80665;
    double T = T0 - L * std::min(h, 11000.0);
    return rho0 * std::pow(T/T0, g/(R*L));
}

// 分段经验阻力系数 Cd(Mach)
inline double dragCoefficient(double v) const{
    double Mach = v / 340.0;
    if (Mach < 0.8)      return 0.295;
    else if (Mach < 1.2) return 0.35;
    else                 return 0.20;
}
  // 在 ResistanceCompensator.hpp 中，新增成员并构造：
  //   double dragCoeff;  // = 0.5 * rho * Cd * A / mass;
  //   double mass;
  //   double gravity;
  //   double velocity;
  ResistanceCompensator() noexcept
  {
      gravity            = 9.80665;      // m/s^2
      projectileMass     = 0.041;        // kg
      projectileArea     = M_PI * std::pow(0.0425/2.0, 2);  // ≈1.418e-3 m^2
      spinAngularRate    = 0.0;          // rad/s (无 Magnus)

      // 空气及阻力参数
      double rho         = 1.225;        // kg/m^3
      double Cd          = 0.30;         // 无量纲
      double k           = 0.5 * rho * Cd * projectileArea;
      dragCoeff          = k / projectileMass;  // ≈6.36e-3 (1/m)

      // 注意：velocity 由外部设置
  }

  double getFlyingTime(const Eigen::Vector3d &target_position) const noexcept override;

protected:
  double calculateTrajectory(const double x, const double angle) const noexcept override;
  double dragCoeff;  // = 0.5 * rho * Cd * A / mass;
  double gravity;
  double velocity;
  // 阻力相关
  double projectileArea;     // 弹体迎风面积 m^2
  double projectileMass;     // 弹体质量 kg

  // Magnus
  double spinAngularRate;    // 自旋角速度 rad/s（无 Magnus 时设 0）
};

// Factory class for trajectory compensator
class CompensatorFactory {
public:
  static std::unique_ptr<TrajectoryCompensator> createCompensator(const std::string &type) {
    if (type == "ideal") {
      return std::make_unique<IdealCompensator>();
    } else if (type == "resistance") {
      return std::make_unique<ResistanceCompensator>();
    } else {
      return nullptr;
    }
  }

private:
  CompensatorFactory() = delete;
  ~CompensatorFactory() = delete;
};

}  // namespace fyt
#endif
